package com.apes.sms.masterdata.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.query.SqlService;
import com.apes.framework.query.lib.PubToolUtil;
import com.apes.framework.rop.session.SimpleSession;
import com.apes.framework.util.MapUtil;
import com.apes.scm.masterdata.enumeration.model.Enumeration;
import com.apes.scm.masterdata.enumeration.repository.EnumerationRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Brand;
import com.apes.scm.masterdata.product.model.Category;
import com.apes.scm.rbac.model.LocalPermitItem;
import com.apes.scm.rbac.repository.LocalPermitItemRepository;
import com.apes.sms.masterdata.model.SupplierProduct;
import com.apes.sms.masterdata.repository.SupplierProductRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * Created by lishikun on 2021/12/23 16:18
 */
@Service(value = "supplierProductService")
public class SupplierProductService extends DomainService {

    @Autowired
    SupplierProductRepository supplierProductRepository;

    @Autowired
    SqlService sqlService;

    private Map<String, Enumeration> character;

    public static JSONArray tranTypeArray(com.apestech.framework.json.JSONArray array){
        return array.stream().map(item ->tranType((com.apestech.framework.json.JSONObject) item)).collect(Collectors.toCollection(JSONArray::new));
    }

    /**
     * 修改
     * @param request
     * @return
     */
    public SupplierProduct update(SimpleRequest request) {
        SupplierProduct supplierProduct = supplierProductRepository.saveAndFlush(toSupplierProductModel(request.getJO().getJSONObject("result")));
        return supplierProduct;
    }



    /**
     * 修改价格和库存
     * @param request
     * @return
     */
    public SupplierProduct updatePriceAndStock(SimpleRequest request) {
        JSONObject param = request.getJO().getJSONObject("result");
        SupplierProduct s = supplierProductRepository.findOne(param.getString("ID"));
        SupplierProduct supplierProduct = (SupplierProduct) s.clone();
//        if (supplierProduct.getVersion() != param.getIntValue("VERSION")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        supplierProduct.setUntaxPrice(param.getDoubleValue("UNTAX_PRICE"));
        supplierProduct.setVersion(param.getIntValue("VERSION"));
        supplierProduct.setInventoryQuantity(param.getDoubleValue("INVENTORY_QUANTITY"));
        return supplierProductRepository.saveAndFlush(supplierProduct);
    }

    /**
     * 删除
     * @param request
     * @return
     */
    public SupplierProduct delete(SimpleRequest request) {
        JSONObject param = request.getJO().getJSONObject("result");
        SupplierProduct supplierProduct = supplierProductRepository.findOne(param.getString("ID"));
        if (supplierProduct.getVersion() != param.getIntValue("VERSION")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        supplierProduct.setState("delete");
        return supplierProductRepository.saveAndFlush(supplierProduct);
    }

    /**
     * 上架
     * @param request
     * @return
     */
    public SupplierProduct onShelf(SimpleRequest request) {
        JSONObject param = request.getJO().getJSONObject("result");
        SupplierProduct s = supplierProductRepository.findOne(param.getString("ID"));
        SupplierProduct supplierProduct = (SupplierProduct) s.clone();
        if (supplierProduct.getVersion() != param.getIntValue("VERSION")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        supplierProduct.setState("onShelf");
        return supplierProductRepository.saveAndFlush(supplierProduct);
    }


    /**
     * 上架全部
     * @param request
     * @return
     */
    public String onShelfAllBySupplier(SimpleRequest request) {
        JSONObject param = request.getJO().getJSONObject("result");
        PartyRole supplier = getSupplierByPost(request);
        AtomicInteger page = new AtomicInteger();
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        while (true) {
            List<SupplierProduct> supplierProducts = supplierProductRepository.findAllBySupplierAndState(supplier.getId(), "toBeShelf", PageRequest.of(page.get(), 1000, sort)).getContent();
            supplierProducts.stream().forEach(supplierProduct -> {
                supplierProduct = (SupplierProduct)supplierProduct.clone();
                supplierProduct.setState("onShelf");
                invoke("sms.supplierProduct.save", supplierProduct);
            });
            if (supplierProducts.size() < 1000) {
                break;
            }
            page.getAndIncrement();
        }
        return "上架成功";
    }

    /**
     * 下架
     * @param request
     * @return
     */
    public SupplierProduct offShelf(SimpleRequest request) {
        JSONObject param = request.getJO().getJSONObject("result");
        SupplierProduct s = supplierProductRepository.findOne(param.getString("ID"));
        SupplierProduct supplierProduct = (SupplierProduct) s.clone();
        if (supplierProduct.getVersion() != param.getIntValue("VERSION")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        supplierProduct.setState("toBeShelf");
        return supplierProductRepository.saveAndFlush(supplierProduct);
    }

    /**
     * 下架全部
     * @param request
     * @return
     */
    public String offShelfAllBySupplier(SimpleRequest request) {
        PartyRole supplier = getSupplierByPost(request);
        AtomicInteger page = new AtomicInteger();
        Sort sort = new Sort(Sort.Direction.ASC, "id");
        while (true) {
            List<SupplierProduct> supplierProducts = supplierProductRepository.findAllBySupplierAndState(supplier.getId(), "onShelf", PageRequest.of(page.get(), 1000, sort)).getContent();
                supplierProducts.stream().forEach(supplierProduct -> {
                supplierProduct = (SupplierProduct)supplierProduct.clone();
                supplierProduct.setState("toBeShelf");
                invoke("sms.supplierProduct.save", supplierProduct);
            });
            if (supplierProducts.size() < 1000) {
                break;
            }
            page.getAndIncrement();
        }
        return "下架成功";
    }

    /**
     * 批量上传供应商商品
     * @param request
     * @return
     */
    public Object batchUpload(SimpleRequest request) {
        return operation("batchUpload", request);
    }

    /**
     * 批量更新供应商商品
     * @param request
     * @return
     */
    public Object batchUpdate(SimpleRequest request) {
        return operation("batchUpdate", request);
    }

    /**
     * 批量更新供应商商品库存价格
     * @param request
     * @return
     */
    public Object batchUpdatePAS(SimpleRequest request) {
        return operation("batchUpdatePAS", request);
    }

    /**
     * 批量商品退回
     * @param request
     * @return
     */
    public Object batchGoBack(SimpleRequest request) {
        return operation("batchGoBack", request);
    }

    /**
     * 批量商品审核
     * @param request
     * @return
     */
    public Object batchApprove(SimpleRequest request) {
        return operation("batchApprove", request);
    }

    /**
     * 根据类型操作
     * @param type
     * @param request
     * @return
     */
    private Map operation(String type, SimpleRequest request) {
        List<SupplierProduct> supplierProductList = getExcelData(request, type);
        Map data = checkData(supplierProductList, type);
        List<SupplierProduct> saveParamMap = (List<SupplierProduct>) data.get("saveParam");
        List returnParamMap = (List) data.get("returnParam");
        supplierProductRepository.save(saveParamMap);
        Map param = new HashMap();
        param.put("saveSize", saveParamMap.size());
        param.put("returnSize", returnParamMap.size());
        param.put("returnParam", returnParamMap);
        return param;
    }

    /**
     * 获取Excel数据
     * @param request
     * @param type
     * @return
     */
    private List<SupplierProduct> getExcelData(SimpleRequest request, String type) {
        HashMap map = new HashMap();
        List<SupplierProduct> supplierProductList = new ArrayList<>();//返回值
        JSONObject importData = request.get("importData");//Excel信息
        List<LocalPermitItem> localPermitItems = SpringManager.getBean(LocalPermitItemRepository.class).find(request.getPostId(), "pp_search", "pt_supplier");
        if (character == null)
            character = SpringManager.getBean(EnumerationRepository.class).findByType("character").stream().collect(Collectors.toMap(Enumeration::getDescription, e -> e));
        String orgId = localPermitItems.size() != 0 ? localPermitItems.get(0).getOrgId() : "";
        PartyRole supplier = new PartyRole();
        supplier.setId(orgId);
        importData.forEach((k, v) -> {
            JSONArray excl = (JSONArray) v;
            JSONArray header = (JSONArray) excl.get(0); //表格头部
            for (int i = 0; i < excl.size(); i++) {  //遍历每一行
                if (i == 0) continue; //跳过首行
                JSONArray lineData =  excl.getJSONArray(i); //当前行
                if (lineData.size() == 0) continue;
                SupplierProduct supplierProduct = this.getExcelElement(lineData, header, type, supplier);
                supplierProductList.add(supplierProduct);
            }
        });
        return supplierProductList;

    }

    /** 获取excel元素
     * @param data 数据
     * @param header 头
     * @param type 类型
     * @param supplier 供应商
     * @return
     */
    private SupplierProduct getExcelElement(JSONArray data, JSONArray header, String type, PartyRole supplier) {

        if("batchUpload".equals(type)) {
            return getBatchUploadExcelElement(data, header, supplier);
        } else if ("batchUpdate".equals(type)) {
            return getBatchUpdateExcelElement(data, header, supplier);
        } else if ("batchUpdatePAS".equals(type)) {
            return getBatchUpdatePASExcelElement(data, header, supplier);
        } else if ("batchGoBack".equals(type)) {
            return getBatchGoBackExcelElement(data, header, supplier);
        } else if ("batchApprove".equals(type)) {
            return getBatchApprove(data, header, supplier);
        }
        return null;
    }

    public Object findAll(SimpleRequest request) {
        JSONObject jo = request.getJO();
        List<String> orders = Stream.of("toBeImproved","toBeAudit", "toBeShelf", "onShelf").collect(Collectors.toList());
        JSONArray array = getObjects(request,"supplierProduct.query",true); //对数据进行查询
        JSONArray headOneArray = getObjects(request,"supplierProduct.qryHeadOne",false); //对数据进行查询
        JSONObject totalJson = null;
        if(array != null && array.size() != 0){
            totalJson = array.getJSONObject(0);
            array.remove(0);
        }
        for (Object o : array) {
            JSONObject jsonObject =(JSONObject)o;
            jsonObject.put("innerBusinessKey", jsonObject.getString("ID"));
            jsonObject.put("innerBusinessType", "SupplierProduct");
        }
        Map reMap = new HashMap();
        List source = headOneArray.stream().map(item->{
            JSONObject itemJson = (JSONObject)item;
            return MapUtil.mapper("id",orders.indexOf(itemJson.getString("ID")),"name",itemJson.getString("NAME"),"value",itemJson.getString("VALUE"),"key",itemJson.getString("KEY")
            ,"api", "sms.supplierProduct.findAll");
        }).collect(Collectors.toList());
        sortListParam(source);
        reMap.put("labelList", source);
        reMap.put("total", totalJson == null ? 0 : totalJson.getJSONObject("SYS_PAGE").getInteger("Total"));
        reMap.put("content", array);
        reMap.put("page", totalJson == null ? 0 : totalJson.getJSONObject("SYS_PAGE").getInteger("Page") - 1);
        reMap.put("size", totalJson == null ? 50 : totalJson.getJSONObject("SYS_PAGE").getInteger("Size"));
        reMap.put("pages", totalJson == null ? 0 : totalJson.getJSONObject("SYS_PAGE").getInteger("TotalPage") - 1);
        reMap.put("elements", array.size());
        return reMap;
    }





    private JSONArray getObjects(SimpleRequest re,String address,boolean page) {
        JSONArray array;
        try {
            com.apestech.framework.json.JSONObject json= PubToolUtil.getInput(re);
            //多余参数移除
            removeExtraParam(json);
            SimpleSession session = (SimpleSession)re.getRopRequestContext().getSession();
            if(session!= null) json.put("postId",session.getPostId());

            if(page) {
                Optional.ofNullable(json.get("page")).orElseThrow(()->new RuntimeException("分页查询，请传入page参数"));
                Optional.ofNullable(json.get("size")).orElseThrow(()->new RuntimeException("分页查询，请传入page参数"));
                if(json.getInteger("size") > 2000) new RuntimeException("分页条数不能大于2000");
                json.put("page",json.getInteger("page") == 0 ? json.getInteger("page") + 1 : json.getInteger("page"));
            }else{
                if(json.get("page") != null) json.remove("page");
                if(json.get("size") != null) json.remove("size");
            }
            array = tranTypeArray(Optional.ofNullable(sqlService.queryId(address,json)).orElseGet(()->new com.apestech.framework.json.JSONArray()));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return array;
    }

    public void removeExtraParam(com.apestech.framework.json.JSONObject json)throws Exception {
        json.remove("customAction");
        json.remove("noSum");
        json.remove("queryid");
        json.remove("customQuery");
        List<Map> condition = (List<Map>)json.get("condition");
        List<Map> list = condition.stream().filter(map -> {
            return map.containsValue("LIST");
        }).collect(Collectors.toList());
        if (list.size() == 0) {
            Map map = new HashMap();
            map.put("field", "LIST");
            map.put("operator", "EQ");
            map.put("value", 0);
            condition.add(map);
        }
    }

    public static JSONObject tranType(com.apestech.framework.json.JSONObject json){
        return JSONObject.parseObject(JSON.toJSONString(json));
    }



    private SupplierProduct toSupplierProductModel(JSONObject param) {
        SupplierProduct s = supplierProductRepository.findOne(param.getString("ID"));
        SupplierProduct supplierProduct = (SupplierProduct)s.clone();
        if (supplierProduct.getVersion() != param.getIntValue("VERSION")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        supplierProduct.setBusinessId(param.getString("BUSINESS_ID"));
        supplierProduct.setBrandName(param.getString("BRAND_NAME"));
        if (!(param.get("SUB_QUALITY") instanceof String)) {
            Enumeration subQuality = new Enumeration();
            subQuality.setId(param.getJSONObject("SUB_QUALITY").getString("id"));
            supplierProduct.setSubQuality(subQuality);
        }
        supplierProduct.setPartName(param.getString("PART_NAME"));
        supplierProduct.setOrigin(param.getString("ORIGIN"));
        supplierProduct.setUomName(param.getString("UOM_NAME"));
        supplierProduct.setUniversalPartNumber(param.getString("UNIVERSAL_PART_NUMBER"));
        supplierProduct.setBrandModel(param.getString("BRAND_MODEL"));
        supplierProduct.setProductDescription(param.getString("PRODUCT_DESCRIPTION"));
        supplierProduct.setSizes(param.getString("SIZES"));
        supplierProduct.setPackageContent(param.getString("PACKAGE_CONTENT"));
        if (supplierProduct.getBrandName() != null && supplierProduct.getSubQuality() != null && supplierProduct.getBusinessId() != null) {
            supplierProduct.setState("toBeAudit");
        }
        return supplierProduct;
    }


    private void sortListParam(List source) {
        List<String> orders = Stream.of("待完善","待审核", "待上架", "已上架").collect(Collectors.toList());
        source.sort(((item1, item2) -> {
            String o1 = ((Map) item1).get("name").toString();
            String o2 = ((Map) item2).get("name").toString();
            if (orders.contains(o1) && orders.contains(o2)) {
                if (orders.indexOf(o1) > orders.indexOf(o2)) {
                    return 1;
                } else if (orders.indexOf(o1) == orders.indexOf(o2)) {
                    return 0;
                } else {
                    return -1;
                }
            } else if (orders.contains(o1) && !orders.contains(o2)) {
                return -1;
            } else if (!orders.contains(o1) && orders.contains(o2)) {
                return 1;
            }
            return 0;
        }));
    }


    protected SupplierProduct getBatchUploadExcelElement(JSONArray data, JSONArray header, PartyRole supplier) {
        SupplierProduct supplierProduct = new SupplierProduct();
        supplierProduct.setUuid(data.getString(header.indexOf("唯一编码")));
        supplierProduct.setBusinessId(data.getString(header.indexOf("商家编码")));
        supplierProduct.setBrandName(data.getString(header.indexOf("品牌")));
        supplierProduct.setSubQuality(character.get(data.getString(header.indexOf("品质"))));
        supplierProduct.setPartName(data.getString(header.indexOf("零件名称")));
        supplierProduct.setUniversalPartNumber(data.getString(header.indexOf("通用件号")));
        supplierProduct.setBrandModel(data.getString(header.indexOf("品牌件型号")));
        supplierProduct.setProductDescription(data.getString(header.indexOf("产品描述")));
        supplierProduct.setUomName(data.getString(header.indexOf("单位")));
        supplierProduct.setOrigin(data.getString(header.indexOf("产地")));
        supplierProduct.setSizes(data.getString(header.indexOf("尺寸")));
        supplierProduct.setPackageContent(data.getString(header.indexOf("包装含量")));
        supplierProduct.setInventoryQuantity(data.getDoubleValue(header.indexOf("库存数量")));
        supplierProduct.setUntaxPrice(data.getDoubleValue(header.indexOf("不含税单价")));
        supplierProduct.setState("toBeImproved");
        supplierProduct.setSupplier(supplier);
        return supplierProduct;
    }

    protected SupplierProduct getBatchUpdateExcelElement(JSONArray data, JSONArray header, PartyRole supplier) {
        SupplierProduct supplierProduct = new SupplierProduct();
        supplierProduct.setUuid(data.getString(header.indexOf("唯一编码")));
        supplierProduct.setBusinessId(data.getString(header.indexOf("商家编码")));
        supplierProduct.setBrandName(data.getString(header.indexOf("品牌")));
        supplierProduct.setSubQuality(character.get(data.getString(header.indexOf("品质"))));
        supplierProduct.setPartName(data.getString(header.indexOf("零件名称")));
        supplierProduct.setUniversalPartNumber(data.getString(header.indexOf("通用件号")));
        supplierProduct.setBrandModel(data.getString(header.indexOf("品牌件型号")));
        supplierProduct.setProductDescription(data.getString(header.indexOf("产品描述")));
        supplierProduct.setUomName(data.getString(header.indexOf("单位")));
        supplierProduct.setOrigin(data.getString(header.indexOf("产地")));
        supplierProduct.setSizes(data.getString(header.indexOf("尺寸")));
        supplierProduct.setPackageContent(data.getString(header.indexOf("包装含量")));
        supplierProduct.setSupplier(supplier);
        return supplierProduct;
    }

    protected SupplierProduct getBatchUpdatePASExcelElement(JSONArray data, JSONArray header, PartyRole supplier) {
        SupplierProduct supplierProduct = new SupplierProduct();
        supplierProduct.setSupplier(supplier);
        supplierProduct.setUuid(data.getString(header.indexOf("唯一编码")));
        supplierProduct.setInventoryQuantity(data.getDoubleValue(header.indexOf("库存数量")));
        supplierProduct.setUntaxPrice(data.getDoubleValue(header.indexOf("不含税单价")));
        return supplierProduct;
    }

    private SupplierProduct getBatchGoBackExcelElement(JSONArray data, JSONArray header, PartyRole supplier) {
        SupplierProduct supplierProduct = new SupplierProduct();
        PartyRole partyRole = new PartyRole();
        partyRole.setId(data.getString(header.indexOf("供应商编码")));
        supplierProduct.setUuid(data.getString(header.indexOf("唯一编码")));
        supplierProduct.setRemark(data.getString(header.indexOf("备注")));
        supplierProduct.setSupplier(partyRole);
        return supplierProduct;
    }

    private SupplierProduct getBatchApprove(JSONArray data, JSONArray header, PartyRole supplier) {
        SupplierProduct supplierProduct = new SupplierProduct();
        PartyRole partyRole = new PartyRole();
        partyRole.setId(data.getString(header.indexOf("供应商编码")));
        supplierProduct.setUuid(data.getString(header.indexOf("唯一编码")));
        Brand brand = new Brand();
        brand.setId(data.getString(header.indexOf("对照品牌编码")));
        supplierProduct.setContrastBrand(brand);
        Category category = new Category();
        category.setId(data.getString(header.indexOf("对照配件名称编码")));
        supplierProduct.setCategory(category);
        supplierProduct.setSupplier(partyRole);
        supplierProduct.setOriginalFactoryCode(data.getString(header.indexOf("原厂零件号")));
        supplierProduct.setContrastOrigin(data.getString(header.indexOf("对照产地")));
        supplierProduct.setContrastPackageContent(data.getString(header.indexOf("对照包装含量")));
        return supplierProduct;
    }

    private Map checkData(List<SupplierProduct> supplierProductList, String type) {
        if("batchUpload".equals(type)) {
            return batchUploadCheckData(supplierProductList);
        } else if ("batchUpdate".equals(type)) {
            return batchUpdateCheckData(supplierProductList);
        }else if ("batchUpdatePAS".equals(type)) {
            return batchUpdatePASCheckData(supplierProductList);
        } else if ("batchGoBack".equals(type)) {
            return batchGoBackCheckData(supplierProductList);
        } else if ("batchApprove".equals(type)) {
            return batchApproveCheckData(supplierProductList);
        }
        return new HashMap<>();
    }




    private Map batchUploadCheckData(List<SupplierProduct> supplierProductList) {
        List<SupplierProduct> saveParam = new ArrayList<>();
        List<Map> returnParam = new ArrayList<>();//返回值
        List<String> uuids = supplierProductList.stream().map(SupplierProduct::getUuid).collect(Collectors.toList());
        String supplierId = supplierProductList.get(0).getSupplier().getId();
        Map supplierProductMap = new HashMap<>();
        for (int i = 0; i <= uuids.size()/1000; i++) {
            supplierProductMap.putAll(
                    supplierProductRepository.findAllByUuidAndSupplierId(uuids.subList(i*1000, (i == uuids.size()/1000)? uuids.size() : (i+1)*1000 ), supplierId)
                    .stream()
                    .collect(Collectors.toMap(SupplierProduct::getUuid, supplierProduct -> supplierProduct)));
        }
        for (SupplierProduct supplierProduct : supplierProductList) {
            String message = "";
            Map jsonObject = MapUtil.mapped(supplierProduct);
            if (supplierProductMap.containsKey(supplierProduct.getUuid())) {
                message = "唯一编码已存在，请勿重复导入商品";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            } else if (supplierProduct.getSubQuality() == null) {
                message = "品质未按规则填写，请填写：原厂(4S店)件、非原厂(4S店)件、品牌件、拆车件、再制造件、其他件";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            } else saveParam.add(supplierProduct);
        }
        Map hashMap = new HashMap<>();
        hashMap.put("saveParam", saveParam);
        hashMap.put("returnParam", returnParam);
        return hashMap;
    }

    private Map batchUpdateCheckData(List<SupplierProduct> supplierProductList) {
        List<SupplierProduct> saveParam = new ArrayList<>();
        List<Map> returnParam = new ArrayList<>();//返回值
        List<String> uuids = supplierProductList.stream().map(SupplierProduct::getUuid).collect(Collectors.toList());
        String supplierId = supplierProductList.get(0).getSupplier().getId();
        Map<String, SupplierProduct> supplierProductMap = new HashMap<>();
        for (int i = 0; i <= uuids.size()/1000; i++) {
            supplierProductMap.putAll(
                    supplierProductRepository.findAllByUuidAndSupplierId(uuids.subList(i*1000, (i == uuids.size()/1000)? uuids.size() : (i+1)*1000 ), supplierId)
                            .stream()
                            .collect(Collectors.toMap(SupplierProduct::getUuid, supplierProduct -> supplierProduct)));
        }

        for (SupplierProduct supplierProduct : supplierProductList) {
            String message = "";
            SupplierProduct supplierProduct1 = supplierProductMap.get(supplierProduct.getUuid());
            Map jsonObject = MapUtil.mapped(supplierProduct);
            if (supplierProduct1 == null) {
                message = "未找到修改商品，商品唯一编码不存在";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            } else if (supplierProduct1.getSubQuality() == null) {
                message = "品质未按规则填写，请填写：原厂(4S店)件、非原厂(4S店)件、品牌件、拆车件、再制造件、其他件";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            } else if(supplierProduct1.getState().equals("toBeAudit")) {
                message = "当前状态处于【待审核】，请等候审核完成后再修改";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            }
            else if (supplierProduct1.getSupplierPlatformSource() != null && supplierProduct1.getSupplierPlatformSource().length() > 1) {
                message = "第三方平台数据，请在第三方平台更新后等待系统同步，暂不支持导入更新第三方平台数据";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            }

            else {
                supplierProduct1.setBusinessId(supplierProduct.getBusinessId());
                supplierProduct1.setBrandName(supplierProduct.getBrandName());
                supplierProduct1.setSubQuality(supplierProduct.getSubQuality());
                supplierProduct1.setPartName(supplierProduct.getPartName());
                supplierProduct1.setUniversalPartNumber(supplierProduct.getUniversalPartNumber());
                supplierProduct1.setBrandModel(supplierProduct.getBrandModel());
                supplierProduct1.setProductDescription(supplierProduct.getProductDescription());
                supplierProduct1.setUomName(supplierProduct.getUomName());
                supplierProduct1.setOrigin(supplierProduct.getOrigin());
                supplierProduct1.setSizes(supplierProduct.getSizes());
                supplierProduct1.setPackageContent(supplierProduct.getPackageContent());
                if (supplierProduct1.getBrandName() != null && supplierProduct1.getSubQuality() != null && supplierProduct1.getBusinessId() != null) {
                    supplierProduct1.setState("toBeAudit");
                }
                saveParam.add(supplierProduct1);
            }
        }
        Map hashMap = new HashMap<>();
        hashMap.put("saveParam", saveParam);
        hashMap.put("returnParam", returnParam);
        return hashMap;
    }

    /**
     * 批量跟新库存价格数据检查
     * @param supplierProductList
     * @return
     */
    private Map batchUpdatePASCheckData(List<SupplierProduct> supplierProductList) {
        List<SupplierProduct> saveParam = new ArrayList<>();
        List<Map> returnParam = new ArrayList<>();//返回值
        List<String> uuids = supplierProductList.stream().map(SupplierProduct::getUuid).collect(Collectors.toList());
        String supplierId = supplierProductList.get(0).getSupplier().getId();
        Map<String, SupplierProduct> supplierProductMap = new HashMap<>();
        for (int i = 0; i <= uuids.size()/1000; i++) {
            supplierProductMap.putAll(
                    supplierProductRepository.findAllByUuidAndSupplierId(uuids.subList(i*1000, (i == uuids.size()/1000)? uuids.size() : (i+1)*1000 ), supplierId)
                            .stream()
                            .collect(Collectors.toMap(SupplierProduct::getUuid, supplierProduct -> supplierProduct)));
        }

        for (SupplierProduct supplierProduct : supplierProductList) {
            String message = "";
            SupplierProduct supplierProduct1 = supplierProductMap.get(supplierProduct.getUuid());
            Map jsonObject = MapUtil.mapped(supplierProduct);
            if (supplierProduct1 == null) {
                message = "未找到修改商品，商品唯一编码不存在";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            }  else if (supplierProduct1.getSupplierPlatformSource() != null && supplierProduct1.getSupplierPlatformSource().length() > 1) {
                message = "第三方平台数据，请在第三方平台更新后等待系统同步，暂不支持导入更新第三方平台数据";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            } else {
                supplierProduct1.setInventoryQuantity(supplierProduct.getInventoryQuantity());
                supplierProduct1.setUntaxPrice(supplierProduct.getUntaxPrice());
                saveParam.add(supplierProduct1);
            }
        }
        Map hashMap = new HashMap<>();
        hashMap.put("saveParam", saveParam);
        hashMap.put("returnParam", returnParam);
        return hashMap;
    }

    /**
     * 批量退回数据检查
     * @param supplierProductList
     * @return
     */
    private Map batchGoBackCheckData(List<SupplierProduct> supplierProductList) {
        List<SupplierProduct> saveParam = new ArrayList<>();
        List<Map> returnParam = new ArrayList<>();//返回值
        String supplierId = supplierProductList.get(0).getSupplier().getId();
        Map<String, SupplierProduct> supplierProductMap = new HashMap<>();
        Map collect = supplierProductList.stream().collect(Collectors.groupingBy(supplierProduct -> {
            return supplierProduct.getSupplier().getId();
        }));
        Set<String> keySet = collect.keySet();
        Map supplier = new HashMap();
        for (String s : keySet) {
            Object id = invoke("cm.supplier.findParty", MapUtil.mapper("id", s));
            supplier.put(s, id);
            List<String> uuids = ((List<SupplierProduct>)collect.get(s)).stream().map(SupplierProduct::getUuid).collect(Collectors.toList());
            for (int i = 0; i <= uuids.size()/1000; i++) {
                supplierProductMap.putAll(
                        supplierProductRepository.findAllByUuidAndSupplierId(uuids.subList(i*1000, (i == uuids.size()/1000)? uuids.size() : (i+1)*1000 ), supplierId)
                                .stream()
                                .collect(Collectors.toMap(SupplierProduct::getUuid, supplierProduct -> supplierProduct)));
            }
        }

        for (SupplierProduct supplierProduct : supplierProductList) {
            String message = "";
            SupplierProduct supplierProduct1 = supplierProductMap.get(supplierProduct.getUuid());
            Map jsonObject = MapUtil.mapped(supplierProduct);
            if (collect.get(supplierProduct.getSupplier().getId()) == null) {
                message = "供应商编码不存在";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            } else if (supplierProduct1 == null) {
                message = "未在该供应商名下找到该商品";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            }  else if (!supplierProduct1.getState().equals("toBeAudit")) {
                message = "该商品未处于“待审核”状态，不可审核，请检查商品状态";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            }  else if (supplierProduct.getRemark() == null || supplierProduct.getRemark().length() == 0) {
                message = "请填写备注以注明退回原因";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            } else {
                supplierProduct1.setRemark(supplierProduct.getRemark());
                supplierProduct1.setState("toBeImproved");
                saveParam.add(supplierProduct1);
            }
        }
        Map hashMap = new HashMap<>();
        hashMap.put("saveParam", saveParam);
        hashMap.put("returnParam", returnParam);
        return hashMap;
    }

    private Map batchApproveCheckData(List<SupplierProduct> supplierProductList) {
        List<SupplierProduct> saveParam = new ArrayList<>();
        List<Map> returnParam = new ArrayList<>();//返回值
        String supplierId = supplierProductList.get(0).getSupplier().getId();
        Map<String, SupplierProduct> supplierProductMap = new HashMap<>();
        Map collect = supplierProductList.stream().collect(Collectors.groupingBy(supplierProduct -> {
            return supplierProduct.getSupplier().getId();
        }));
        Set<String> keySet = collect.keySet();
        Map supplier = new HashMap();
        for (String s : keySet) {
            Object id = invoke("cm.supplier.findParty", MapUtil.mapper("id", s));
            supplier.put(s, id);
            List<String> uuids = ((List<SupplierProduct>)collect.get(s)).stream().map(SupplierProduct::getUuid).collect(Collectors.toList());
            for (int i = 0; i <= uuids.size()/1000; i++) {
                supplierProductMap.putAll(
                        supplierProductRepository.findAllByUuidAndSupplierId(uuids.subList(i*1000, (i == uuids.size()/1000)? uuids.size() : (i+1)*1000 ), supplierId)
                                .stream()
                                .collect(Collectors.toMap(SupplierProduct::getUuid, supplierProduct -> supplierProduct)));
            }
        }

        for (SupplierProduct supplierProduct : supplierProductList) {
            String message = "";
            SupplierProduct supplierProduct1 = supplierProductMap.get(supplierProduct.getUuid());
            Map jsonObject = MapUtil.mapped(supplierProduct);
            Brand brand = (Brand)invoke("cm.dataCenter.brand.findOne", MapUtil.mapper("id",supplierProduct.getContrastBrand().getId()));
            Object category = invoke("cm.dataCenter.category.findOne", MapUtil.mapper("id", supplierProduct.getCategory().getId()));
            if (collect.get(supplierProduct.getSupplier().getId()) == null) {
                message = "供应商编码不存在";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            } else if (supplierProduct1 == null) {
                message = "未在该供应商名下找到该商品";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            }  else if (!supplierProduct1.getState().equals("toBeAudit")) {
                message = "该商品未处于“待审核”状态，不可审核，请检查商品状态";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            }  else if (brand == null) {
                message = "该对照品牌不存在或已失效,请重新对照";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            }  else if (brand != null && (brand.getSubQuality() == null || brand.getCharacter() == null)) {
                message = "该对照品牌未填写品质或细分品质";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            } else if (category == null) {
                message = "该配件名称不存在或已失效,请重新对照";
                jsonObject.put("message", message);
                returnParam.add(jsonObject);
            } else {
                supplierProduct1.setContrastBrand(supplierProduct.getContrastBrand());
                supplierProduct1.setCategory(supplierProduct.getCategory());
                supplierProduct1.setOriginalFactoryCode(supplierProduct.getOriginalFactoryCode());
                supplierProduct1.setContrastOrigin(supplierProduct.getContrastOrigin());
                supplierProduct1.setContrastPackageContent(supplierProduct.getContrastPackageContent());
                supplierProduct1.setState("toBeShelf");
                saveParam.add(supplierProduct1);
            }
        }
        Map hashMap = new HashMap<>();
        hashMap.put("saveParam", saveParam);
        hashMap.put("returnParam", returnParam);
        return hashMap;
    }

    private PartyRole getSupplierByPost(SimpleRequest request) {
        List<LocalPermitItem> localPermitItems = SpringManager.getBean(LocalPermitItemRepository.class).find(request.getPostId(), "pp_search", "pt_supplier");
        if (localPermitItems.isEmpty()) {
            throw new RuntimeException("未找到当前操作人对应的供应商,请切换");
        }
        String orgId = localPermitItems.get(0).getOrgId();
        PartyRole supplier = new PartyRole();
        supplier.setId(orgId);
        return supplier;
    }

    private SupplierProduct save(SimpleRequest request) {
        SupplierProduct supplierProduct = request.getO(SupplierProduct.class);
        return supplierProductRepository.saveAndFlush(supplierProduct);
    }
}
